<?php
/**
 * 购物车
 * */

use app\config\Db;
use Core\Common\Common;
use Core\Result\Result;
require_once "Order.php";
/**
 * 加入购物车 TODO
 *
 */
function addCart($data)
{
    $user_id = Common::getUser_id($data);
    $sku_id = $data['sku_id'];
    $goods_id = $data['goods_id'];
    $quantity = $data['order_number'];

    if ($quantity <= 0) Result::error("订单数量错误");
    if ($sku_id <= 0 || $goods_id <=0) Result::error("未知商品");
    $db = new Db("host");
    $userInfo = $db->find("select ui.user_id,ui.user_group from user_info as ui inner join user_extra_info as uei on uei.user_id=ui.user_id inner join user_authentication as ua on ua.id=ui.user_id where ui.user_id=$user_id");
    if (!$userInfo) Result::error("用户信息不存在");
    $goodsSkuInfo = $db->find("select gos.*,g.unreal_sales_volume,g.goods_type,g.is_top,g.is_adopt,g.is_task,g.is_delete,g.is_task,g.shop_id from ysmz_shop_goods_sku as gos inner join ysmz_shop_goods as g on gos.goods_id=g.goods_id where gos.sku_id=$sku_id and g.goods_id = $goods_id limit 1");
    if ($goodsSkuInfo['is_top'] == 0 || empty($goodsSkuInfo)) Result::error("商品已下架");
    if ($goodsSkuInfo['is_adopt'] == 0 ) Result::error("商品未审核");
    if ($goodsSkuInfo['is_delete'] == 1) Result::error("商品已删除");
    $fileInfo = $db->find("select file_id,storage,`domain`,file_path from `ysmz_file` where `file_id`={$goodsSkuInfo['sku_img_id']} limit 1");
    $pic_thumb = Common::fileUrl($fileInfo);
    $market_price = $goodsSkuInfo['sku_old_price'];
    $original_price = $goodsSkuInfo['sku_sell_price'];
    $cartInfo = $db->find("select `cart_id`,`quantity` from ysmz_cart where `user_id`=$user_id and `sku_id`=$sku_id and `goods_id` = $goods_id and `original_price` = $original_price limit 1");
    $update_time = time();
    if(empty($cartInfo)){
        //添加购物车
        $specArr = json_decode($goodsSkuInfo['spec_info']);
        foreach ($specArr as $kk => $vv) {
            $skuId[] = $kk;
            $skuId[] = $vv;
        }
        $skuId = implode(',', array_unique($skuId));
        $specInfo = $db->query("select name from `ysmz_shop_goods_spec` where spec_id in($skuId) and is_delete=0");
        $sku_data = '';
        foreach ($specInfo as $sk => $sv){
            $sku_data .= $sv['name'].";";
        }
        if(!empty($sku_data)){
            $sku_data = mb_substr($sku_data, 0, -1);
        }
        $product_type = $goodsSkuInfo['is_task'] ==0 ? 1:2;
        $shop_id = $goodsSkuInfo['shop_id'];
        $type = $goodsSkuInfo['goods_type'];
        $CartSql = "INSERT INTO `ysmz_cart` (`user_id`, `goods_id`, `pic_thumb`, `market_price`, `original_price`, `quantity`, `sku_id`, `sku_data`, `product_type`, `shop_id`, `type`, `update_time`) VALUES ($user_id, $goods_id, '$pic_thumb',$market_price, $original_price, $quantity, $sku_id, '$sku_data', $product_type, $shop_id, $type, $update_time)";
    }else{
        //增加数量
        $CartSql = "UPDATE `ysmz_cart` SET `quantity` = `quantity` + $quantity,`update_time` = $update_time WHERE `user_id`=$user_id and `sku_id`=$sku_id and `goods_id` = $goods_id and `original_price` = $original_price";
    }
    $db->startTrans();
    try {
        if (!$db->save($CartSql)) Common::exception('购物车添加失败');
        $db->commit();
        Result::success();
    } catch (\Exception $e) {
        $db->rollback();
        Result::error($e->getMessage());
    }
}
/**
 * 购物车获取结算数据
 */
function cartCheckout($data)
{
    $cart_id = $data['cart_ids'];
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $userInfo = $db->find("select `user_id` from `user_info` where `user_id`=$user_id");
    if (!$userInfo) Result::error("用户信息丢失，请重新登录");

    $cart = $db->query("select c.`cart_id`,s.`shop_id`,`shop_title`,`shop_logo`,`contact_mobile`,`description`,`kefu_weixin`,`kefu_phone`,`coordinate`,`cust_addr` from `ysmz_cart` as c inner join  `ysmz_shop` as s on c.shop_id = s.shop_id where c.`user_id` = $user_id and `cart_id` in($cart_id) and `status` =1 group by c.`shop_id`");
    foreach ($cart as $k => $v) {
        $shippingTotalFee = [];
        $cartList = $db->query("select `cart_id`,`pic_thumb`,`market_price`,`original_price`,`quantity`,yc.`sku_id`,`sku_data`,`product_type`,yc.`shop_id`,`type`,yc.`update_time`,sgs.`sku_sell_price`,sgs.`sku_name`,sgs.goods_id,sg.is_top,sg.is_adopt,sg.is_delete from ysmz_cart as yc inner join `ysmz_shop_goods_sku` as sgs on yc.sku_id = sgs.sku_id inner join `ysmz_shop_goods` as sg on sgs.goods_id = sg.goods_id where yc.`user_id` = $user_id and `cart_id` in($cart_id) and yc.shop_id = $v[shop_id]");
        foreach ($cartList as $kk => $vv) {
            $cartList[$kk]['isDisplay'] = true;
            $goodsSql = "select `free_shipping`,`fixed_shipping_fee`,`shipping_tpl_id`,`fixed_shipping_type` from `ysmz_shop_goods` where `goods_id`=$vv[goods_id]";
            $goodsInfo = $db->find($goodsSql);
            if($goodsInfo['free_shipping'] == 1){//免运费
                $shipping_fee = 0;
            }else{
                if($goodsInfo["fixed_shipping_type"] == 1){
                    $shipping_fee = $goodsInfo["fixed_shipping_fee"];//固定运费
                }else{
                    $shippingData["order_price"] = $vv["sku_sell_price"];
                    $shippingData["order_number"] = $vv["quantity"];
                    $shippingData["shipping_tpl_id"] = $goodsInfo["shipping_tpl_id"];
                    $shipping_fee = shippingTpl($shippingData);
                    $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["order_price"] += $vv["sku_sell_price"]*$vv["quantity"];
                    $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["order_number"] = 1;
                    if($shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["shipping_tpl_id"] == $goodsInfo["shipping_tpl_id"] && $shipping_fee >0){
                        $shipping_fee = 0;
                    }
                    $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["shipping_tpl_id"] = $goodsInfo["shipping_tpl_id"];
                    if($shipping_fee > 0 ){
                        $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["ids"] = $kk;
                        $cartList[$kk]["shipping_tpl_id"] = $goodsInfo["shipping_tpl_id"];
                    }
                }
            }
            $cartList[$kk]['fixed_shipping_fee'] = $shipping_fee;
            $cartList[$kk]['new_price'] = $vv['sku_sell_price'];
            $cartList[$kk]['total_price'] = round($vv['quantity'] * $vv['sku_sell_price'],2);
            if($vv["is_adopt"] == 0 || $vv["is_top"] == 0 || $vv["is_delete"] == 1){
                $cartList[$kk]['isDisplay'] = false;
            }
        }
        foreach ($shippingTotalFee as $kkk => $vvv) {
            $vvv["shipping_tpl_id"] = $kkk;
            $shippingTpl = shippingTpl($vvv);
            if($shippingTpl == 0){
                if(is_numeric($vvv["ids"]) && $vvv["ids"] >= 0 && $vvv["shipping_tpl_id"] = $cartList[$vvv["ids"]]["shipping_tpl_id"]){
                    $cartList[$vvv["ids"]]['fixed_shipping_fee'] = 0;
                }
            }
        }
        $cart[$k]["cartList"] = $cartList;
    }
    Result::success($cart);
}
/**
 * 购物车列表 TODO
 *
 */
function cartList($data)
{
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $cart = $db->query("select c.`cart_id`,s.`shop_id`,`shop_title`,`shop_logo`,`contact_mobile`,`description`,`kefu_weixin`,`kefu_phone`,`coordinate`,`cust_addr` from `ysmz_cart` as c inner join  `ysmz_shop` as s on c.shop_id = s.shop_id where `user_id`=$user_id and `status` =1 group by c.`shop_id` order by c.update_time desc");
    foreach ($cart as $k => $v) {
        $cartList = $db->query("select `cart_id`,`pic_thumb`,`market_price`,`original_price`,`quantity`,yc.`sku_id`,`sku_data`,`product_type`,yc.`shop_id`,`type`,yc.`update_time`,sg.`section_id`,sgs.`sku_sell_price`,sgs.`sku_name`,sgs.goods_id,sg.is_top,sg.is_adopt,sg.is_delete from ysmz_cart as yc inner join `ysmz_shop_goods_sku` as sgs on yc.sku_id = sgs.sku_id inner join `ysmz_shop_goods` as sg on sgs.goods_id = sg.goods_id where yc.`user_id`=$user_id and yc.`shop_id`=$v[shop_id] order by yc.update_time desc");
        foreach ($cartList as $kk => $vv) {
            $cartList[$kk]['isDisplay'] = true;
            $goodsSql = "select `free_shipping`,`fixed_shipping_fee` from `ysmz_shop_goods` where `goods_id`=$vv[goods_id]";
            $goodsInfo = $db->find($goodsSql);
            $cartList[$kk]['free_shipping'] = $goodsInfo['free_shipping'];
            $cartList[$kk]['fixed_shipping_fee'] = $goodsInfo['fixed_shipping_fee'];
            $cartList[$kk]['new_price'] = $vv['sku_sell_price'];
            $cartList[$kk]['total_price'] = round($vv['quantity'] * $vv['sku_sell_price'],2);
            if($vv["is_adopt"] == 0 || $vv["is_top"] == 0 || $vv["is_delete"] == 1){
                $cartList[$kk]['isDisplay'] = false;
            }
        }
        $cart[$k]["cartList"] = $cartList;
    }
    Result::success($cart);
}
/**
 * 编辑购物车 TODO
 * @param $data
 * @return void
 */
function upCart($data)
{
    $user_id = Common::getUser_id($data);
    $type = $data['type'];
    $cart_id = $data['cart_id'];
    $db = new Db("host");
    $cart = $db->find("select `cart_id`,`quantity` from `ysmz_cart` where `user_id`=$user_id and `cart_id` =$cart_id");
    if(empty($cart)){
        Result::error("购物车商品失效");
    }
    $update_time = time();
    if($type == 1){
        $CartSql = "UPDATE `ysmz_cart` SET `quantity` = `quantity` + 1,`update_time` = $update_time WHERE `user_id`=$user_id and `cart_id`=$cart_id";
    }else{
        if($cart["quantity"] <= 1){
            Result::error("无效操作");
        }
        $CartSql = "UPDATE `ysmz_cart` SET `quantity` = `quantity` - 1,`update_time` = $update_time WHERE `user_id`=$user_id and `cart_id`=$cart_id";
    }
    $db->startTrans();
    try {
        if (!$db->save($CartSql)) Common::exception('购物车编辑失败');
        $db->commit();
        Result::success();
    } catch (\Exception $e) {
        $db->rollback();
        Result::error($e->getMessage());
    }
}
/**
 * 删除购物车 TODO
 * @param $data
 * @return void
 */
function delCart($data)
{
    $user_id = Common::getUser_id($data);
    $cart_id = $data['cart_id'];
    if(empty($cart_id)){
        Result::error("请勾选购物车商品操作");
    }
    $db = new Db("host");
    $cart = $db->query("select `cart_id`,`quantity` from `ysmz_cart` where `user_id`=$user_id and `cart_id` in($cart_id)");
    if(empty($cart)){
        Result::error("购物车商品失效");
    }
    $deleSql = "delete from `ysmz_cart` where `user_id` =$user_id and `cart_id` in($cart_id)";
    $db->startTrans();
    try {
        if (!$db->save($deleSql)) Common::exception('购物车删除失败');
        $db->commit();
        Result::success();
    } catch (\Exception $e) {
        $db->rollback();
        Result::error($e->getMessage());
    }
}
